<template>
  <div class="app-container">
    <el-row class="library-row">
      <el-col :span="4">
        <el-input placeholder="请输入内容" v-model="search" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="searchList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="3" :offset="17" class="add">
        <el-button @click="addBooks" type="primary" icon="el-icon-plus">添加角色</el-button>
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      stripe
      @sort-change="sort"
      style="width: 100%"
      :default-sort="{prop: 'role_id', order: 'descending'}"
    >
      <el-table-column prop="role_id" label="#" width="100" sortable="custom"></el-table-column>
      <el-table-column prop="role_name" label="角色名称"></el-table-column>
      <el-table-column fixed="right" label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editor(scope.row)">编辑</el-button>
          <el-button @click="del(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="total">
      <el-pagination
        @current-change="currentPage"
        background
        :page-size="20"
        layout="prev, pager, next"
        :total="total"
      ></el-pagination>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog :title="title" class="school" :close-on-click-modal="false"  width="40%" :visible.sync="dialogFormVisible">
      <el-form :model="formData" ref="formSave" :rules="rules">
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="formData.role_name" placeholder="请填写" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色权限">
          <el-row>
            <el-col>
              <el-tree
                :data="data"
                ref="tree"
                :check-strictly="systemNodeFlag"
                :default-expand-all="true"
                show-checkbox
                node-key="menu_id"
                :default-checked-keys="formData.menuids"
                :props="defaultProps"
              ></el-tree>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save('formSave')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  roleList,
  addRole,
  delRole,
  editorRole,
  getNodeList,
  editorRoleList,
} from "@/api/set";

export default {
  data() {
    return {
      title: "添加角色",
      search: "",
      total: 1,
      systemNodeFlag: false,
      isEdit: false,
      form: {
        page: 1,
        page_size: 20,
        role_name: "",
        sort: "",
        order: "",
      },
      formData: {
        role_name: "",
        menuids: [],
      },
      rules: {
        role_name: [
          { required: true, message: "请填写角色名称", trigger: "blur" },
        ],
      },
      id: null,
      dialogFormVisible: false, //新增弹窗
      list: null,
      listLoading: true,
      value: "",
      tableData: [],
      data: [],
      defaultProps: {
        children: "children",
        label: "menu_name",
      },
    };
  },
  mounted() {
    this.fetchData();
    this.getNode();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      roleList().then((response) => {
        this.total = response.total;
        this.tableData = response.data;
      });
    },
    getNode() {
      getNodeList().then((response) => {
        let data = response.data;
        
        this.data =data;
      });
    },
    // 排序及搜索请求
    async changedata(order) {
      let params = {
        page: 1,
        page_size: 20,
        role_name: this.search,
        sort: "role_id",
        order: order,
      };
      let list = await roleList(params);
      this.tableData = list.data;
    },
    // 删除请求
    async delete() {
      let $id = this.id;
      let del = await delRole($id);
      if (del.code == 1) {
        this.$message({
          type: "success",
          message: del.message,
        });
      } else {
        this.$message({
          type: "info",
          message: del.message,
        });
      }
      this.fetchData();
    },
    // 保存新增请求
    async saveData() {
      let data = {
        role_name:this.formData.role_name,
        menuids:this.formData.menuids
      }
      let res = await addRole(data);
      if (res.code == 1) {
        this.$message({
          type: "success",
          message: res.message,
        });
        this.fetchData();
        this.dialogFormVisible = false;
      } else {
        this.$message({
          type: "info",
          message: res.message,
        });
      }
    },
    // 保存编辑请求
    async saveDataEditor() {
      let $id = this.id;
      let data = this.formData;
      let res = await editorRole(data, $id);
      if (res.code == 1) {
        this.$message({
          type: "success",
          message: res.message,
        });
        this.fetchData();
        this.dialogFormVisible = false;
      } else {
        this.$message({
          type: "info",
          message: res.message,
        });
      }
    },
    // 获取编辑请求
    async editorData() {

      this.systemNodeFlag = true;
      let $id = this.id;
      let res = await editorRoleList($id);
      if (res.code == 1) {
        this.$message({
          type: "success",
          message: res.message,
        });
    this.$nextTick(()=>{
  this.formData.role_name=res.data.role.role_name
        this.formData.menuids = res.data.menu_id;   
         this.$refs.tree.setCheckedKeys(res.data.menu_id);
           this.systemNodeFlag= false;
    })

      } else {
        this.$message({
          type: "info",
          message: res.message,
        });
      }
    },
    // 搜索
    searchList() {
      (this.form.page = 1), (this.form.role_name = this.search);
      this.changedata();
    },
    // 添加图书
    addBooks() {
 this.formData.menuids=[]
 console.log(this.$refs.tree)
      this.$nextTick(()=>{
       this.$refs.tree.setCheckedKeys([])
      })
   
      this.dialogFormVisible = true;
      this.title = "添加角色";
      this.formData = {};
    },
    // 编辑
    editor(row) {
      console.log(row);
      this.id = row.role_id;
      this.dialogFormVisible = true;
      this.title = "编辑角色";
      this.editorData();
    },
    // 删除
    del(row) {
      this.id = row.role_id;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delete();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 排序
    sort(val) {
      let order = val.order;
      if (order == "descending") {
        this.form.order = "desc";
      } else if (order == "ascending") {
        this.form.order = "asc";
      } else {
        this.form.order = null;
      }
      this.changedata(this.form.order);
    },
    // 页签
    currentPage(val) {
      this.form.page = val;
      this.changedata();
    },
    // 保存数据
    save(formSave) {
      this.formData.menuids = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      if (this.title == "添加角色") {
        this.saveData();
        console.log(1);
      } else {
        this.saveDataEditor();
        console.log(2);
      }
    },
  },
};
</script>
<style>
.library-row {
  padding: 15px 0;
}
.add {
  display: flex;
  justify-content: flex-end;
}
.el-dialog__body {
  border: 1px solid #ddd;
}
.total {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}
.el-form-item__label {
  float: none;
}
.school .el-select {
  display: inline-block;
  width: 100%;
  position: relative;
}
.el-tree-node__children .el-tree-node__children > div {
  float: left;
}
</style>